package wikisearch.datastructures;

import java.util.*;
import org.jgrapht.*;
import org.jgrapht.graph.*;

public class Graph extends SimpleDirectedWeightedGraph<String, WEdge>{
	
	public Graph() {
		
		super(WEdge.class);
	}
	
	public Graph(Subgraph<String, WEdge, Graph> g) { 
		
		super(WEdge.class);
		for (WEdge e : g.edgeSet()) {
			
			String s = g.getEdgeSource(e);
			String t = g.getEdgeTarget(e);
			if (!this.containsVertex(s)) this.addVertex(s);
			if (!this.containsVertex(t)) this.addVertex(t);
//			addEdge(s, t);
//			addEdge(t, s);
			setEdgeWeight(addEdge(s, t), g.getEdgeWeight(e));

		}
	}
	
	public void addNode(String name) {
		
		if (!containsVertex(name))
			addVertex(name);
	}

	
	public void setEdgeWeight(String nname1, String nname2, double weight) {
		
		removeEdge(nname1, nname2);
		addNode(nname1);
		addNode(nname2);
		setEdgeWeight(addEdge(nname1, nname2), weight);
		setEdgeWeight(addEdge(nname2, nname1), weight);
	}
	
	
	public String getRandomVert() {
		Object [] verts = this.vertexSet().toArray();
		int idx = (int) (((double)verts.length) * Math.random() );
		return verts[idx].toString();
	}
	
	
	public void print() {
		
		Set<WEdge> es = edgeSet();
		for (WEdge e : es) {
			System.out.println("" + e.toString() + " : " + this.getEdgeWeight(e));
		}
	}
	
	public EdgeCompare getComparator() {
		
		return new EdgeCompare();
	}
	
	public class EdgeCompare implements Comparator{

		@Override
		public int compare(Object arg0, Object arg1) {
			
			WEdge e1 = (WEdge) arg0;
			WEdge e2 = (WEdge) arg1;
			
			double e1w = getEdgeWeight(e1);
			double e2w = getEdgeWeight(e2);
			return -Double.compare(e1w, e2w);
		}
		
	}
	
}
